package com.yanqu.road.server.manager.cross.battle;

import com.yanqu.road.dao.impl.activity.dafuweng.CrossDFWUnionDataDaoImpl;
import com.yanqu.road.dao.impl.activity.dafuweng.CrossDFWUnionRecordDaoImpl;
import com.yanqu.road.dao.impl.activity.dafuweng.CrossDFWUserCollectDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.dafuweng.*;
import com.yanqu.road.entity.activity.dafuweng.cross.CrossDfwUnionData;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.activity.dafuweng.eDaFuWengBuildingType;
import com.yanqu.road.entity.enums.activity.dafuweng.eDaFuWengCardType;
import com.yanqu.road.entity.enums.activity.dafuweng.eDaFuWengEventType;
import com.yanqu.road.entity.enums.activity.dafuweng.eDaFuWengParamType;
import com.yanqu.road.entity.enums.eItemId;
import com.yanqu.road.entity.enums.eRedHotNotifyType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.bussiness.activity.DFWActivityBussiness;
import com.yanqu.road.logic.helper.CalcPowerResult;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.monopoly.CrossMonopolyProto;
import com.yanqu.road.pb.monopoly.MonopolyProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityInfoMgr;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.manger.TempCommonMgr;
import com.yanqu.road.server.pb.CrossDaFuWengPb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author wpj
 * @Date 2021/1/5
 */
public class DaFuWengDataMgr extends TempMgr {

    private static Object lockObject = new Object();                // 大锁
    public static final int StepsNum = 72;                          // 地图总格子数
    private static final int reRollWeightDefault = 600;             // 重掷色子默认权重

    private static Map<Integer, DFWConfig> dfwConfigMap = new ConcurrentHashMap<>();
    private static Map<Integer, Map<Integer, CrossDfwUnionData>> dfwGroupDataMap = new ConcurrentHashMap<>();
    private static Map<Integer, Map<Long, MonopolyProto.UnionMemberDollTemp>> dfwUserDollMap = new ConcurrentHashMap<>();
    private static Map<Integer, Map<Integer, List<MonopolyProto.NotifyDollMoveMsg>>> dfwNeedSyncMoveMsg = new ConcurrentHashMap<>();


    public static void updateDoll(int activityId, String unionId, MonopolyProto.UnionMemberDollTemp dollMsg, boolean isMove) {
        Map<Long, MonopolyProto.UnionMemberDollTemp> map = dfwUserDollMap.get(activityId);
        if (map == null) {
            synchronized (lockObject) {
                if (!dfwUserDollMap.containsKey(activityId)) {
                    dfwUserDollMap.put(activityId, new ConcurrentHashMap<>());
                }
                map = dfwUserDollMap.get(activityId);
            }
        }

        MonopolyProto.UnionMemberMoveDataMsg moveData = dollMsg.getMoveData();
        MonopolyProto.UnionMemberMoveDataMsg.Builder builder = moveData.toBuilder();
        builder.setMoveStep(0);
        builder.setSecretBeginPosition(builder.getSecretOverPosition());
        builder.setNormalBeginPosition(builder.getNormalOverPosition());
        MonopolyProto.UnionMemberDollTemp.Builder newDollMsg = dollMsg.toBuilder().setMoveData(builder);
        map.put(newDollMsg.getUserId(), newDollMsg.build());
    }

    public static void sendDollMoveMsg() {
        for (Map.Entry<Integer, Map<Integer, List<MonopolyProto.NotifyDollMoveMsg>>> entry : dfwNeedSyncMoveMsg.entrySet()) {
            int activityId = entry.getKey();
            for (Map.Entry<Integer, List<MonopolyProto.NotifyDollMoveMsg>> entry2 : entry.getValue().entrySet()) {
                int groupId = entry2.getKey();
                List<MonopolyProto.NotifyDollMoveMsg> list = entry2.getValue();
                syncDollMoveMsg(activityId, groupId, list);
            }
        }
    }

    public static void addNotifyMoveMsg(int activityId, MonopolyProto.NotifyDollMoveMsg notifyDollMoveMsg, int groupId) {
        Map<Integer, List<MonopolyProto.NotifyDollMoveMsg>> map = dfwNeedSyncMoveMsg.get(activityId);
        if (map == null) {
            synchronized (lockObject) {
                if (!dfwNeedSyncMoveMsg.containsKey(activityId)) {
                    dfwNeedSyncMoveMsg.put(activityId, new ConcurrentHashMap<>());
                }
                map = dfwNeedSyncMoveMsg.get(activityId);
            }
        }

        List<MonopolyProto.NotifyDollMoveMsg> list = map.get(groupId);
        if (list == null) {
            synchronized (lockObject) {
                if (!map.containsKey(groupId)) {
                    map.put(groupId, new ArrayList<>());
                }
                list = map.get(groupId);
            }
        }

        synchronized (lockObject) {
            list.add(notifyDollMoveMsg);
        }
    }

    private static void syncDollMoveMsg(int activityId, int groupId, List<MonopolyProto.NotifyDollMoveMsg> msgList) {
        if (msgList == null || msgList.size() == 0) {
            return;
        }
        List<MonopolyProto.NotifyDollMoveMsg> tempList;
        synchronized (msgList) {
            tempList = new ArrayList<>(msgList);
            msgList.clear();
        }
        MonopolyProto.SyncDollMoveMsg.Builder syncMsg = MonopolyProto.SyncDollMoveMsg.newBuilder();
        for (MonopolyProto.NotifyDollMoveMsg msg : tempList) {
            syncMsg.addMsg(msg);
        }
        YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_DA_FU_WENG_CROSS_UNION_SYNC_DOLL_MOVE, syncMsg);

        List<Long> serverList = new ArrayList<>();
        if (groupId == UnionActivityGroupHelper.NO_NEED_GROUP_ID) {
            serverList = ActivityInfoMgr.getActivityInfo(activityId).getServerIdList();
        } else {
            UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, groupId);
            if (groupData != null) {
                serverList = new ArrayList<>(groupData.getServerSet());
            }
        }
        for (long serverId : serverList) {
            MessageHelper.sendPacket(serverId, 0, message);
        }
    }

    public static List<MonopolyProto.UnionMemberDollTemp> getDollMsg(int activityId, List<Long> userList) {
        List<MonopolyProto.UnionMemberDollTemp> list = new ArrayList<>();

        Map<Long, MonopolyProto.UnionMemberDollTemp> map = dfwUserDollMap.get(activityId);
        if (map == null) {
            return list;
        }

        for (long userId : userList) {
            MonopolyProto.UnionMemberDollTemp temp = map.get(userId);
            if (temp != null) {
                list.add(temp);
            }
        }

        return list;
    }

    public static void resetUnionAddition() {
        for (Integer activityId : new ArrayList<>(dfwConfigMap.keySet())) {
            DFWConfig config = getDfwConfig(activityId);
            if (config != null) {
                for (Map<Integer, CrossDfwUnionData> map : dfwGroupDataMap.values()) {
                    for (CrossDfwUnionData data : map.values()) {
                        for (String unionId : data.getUnionDataMap().keySet()) {
                            checkUnionAddition(config, unionId);
                        }
                    }
                }
            }
        }
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean save() {
        for (Map<Integer, CrossDfwUnionData> map : dfwGroupDataMap.values()) {
            for (CrossDfwUnionData dfwData : map.values()) {
                // 商会数据
                for (DFWUnionData unionData : dfwData.getUnionDataMap().values()) {
                    if (unionData.isInsertOption()) {
                        new CrossDFWUnionDataDaoImpl().add(unionData);
                    } else if (unionData.isUpdateOption()) {
                        new CrossDFWUnionDataDaoImpl().update(unionData);
                    }
                }
                // 商会记录数据（造谣、祝福）
                for (List<DFWUnionRecord> recordList : dfwData.getZaoYaoMap().values()) {
                    for (int i = 0; i < recordList.size(); i++) {
                        DFWUnionRecord unionRecord = recordList.get(i);
                        if (unionRecord.isInsertOption()) {
                            new CrossDFWUnionRecordDaoImpl().add(unionRecord);
                        } else if (unionRecord.isUpdateOption()) {
                            new CrossDFWUnionRecordDaoImpl().update(unionRecord);
                        }
                    }
                }
                for (List<DFWUnionRecord> recordList : dfwData.getZhuFuMap().values()) {
                    for (int i = 0; i < recordList.size(); i++) {
                        DFWUnionRecord unionRecord = recordList.get(i);
                        if (unionRecord.isInsertOption()) {
                            new CrossDFWUnionRecordDaoImpl().add(unionRecord);
                        } else if (unionRecord.isUpdateOption()) {
                            new CrossDFWUnionRecordDaoImpl().update(unionRecord);
                        }
                    }
                }

                for (Map<String, Map<Integer, Map<Integer, Map<Long, DFWUserCollectData>>>> value : dfwData.getUserCollectDataMap().values()) {
                    for (Map<Integer, Map<Integer, Map<Long, DFWUserCollectData>>> integerMapMap : value.values()) {
                        for (Map<Integer, Map<Long, DFWUserCollectData>> mapMap : integerMapMap.values()) {
                            for (Map<Long, DFWUserCollectData> dfwUserCollectDataMap : mapMap.values()) {
                                for (DFWUserCollectData data : dfwUserCollectDataMap.values()) {
                                    if (data.isInsertOption()) {
                                        new CrossDFWUserCollectDataDaoImpl().add(data);
                                    } else if (data.isUpdateOption()) {
                                        new CrossDFWUserCollectDataDaoImpl().update(data);
                                    }
                                }
                            }
                        }
                    }
                }

                long nowTime = System.currentTimeMillis() / 1000;
                if (nowTime >= (dfwData.getActivityInfo().getEndTime() + 60 * 60)) {
                    if (dfwData.getZaoYaoMap().size() > 0) {
                        getLogger().debug("remove expired data {} {} {}", dfwData.getActivityInfo().getActivityId(), dfwData.getZaoYaoMap().size(), dfwData.getZhuFuMap().size());
                        dfwData.setZaoYaoMap(new ConcurrentHashMap<>());
                        dfwData.setZhuFuMap(new ConcurrentHashMap<>());
                    }

                }
            }
        }
        return true;
    }


    public static List<DFWEvent> getReachEvents(DFWConfig dfwConfig, eDaFuWengBuildingType buildingType) {
        return getEvents(dfwConfig, dfwConfig.getDfwBuildingConfigMap().get(buildingType.getValue()).getReachEventList());
    }

    public static List<DFWEvent> getPassEvents(DFWConfig dfwConfig, eDaFuWengBuildingType buildingType) {
        return getEvents(dfwConfig, dfwConfig.getDfwBuildingConfigMap().get(buildingType.getValue()).getPassEventList());
    }

    public static List<DFWEvent> getEvents(DFWConfig dfwConfig, List<Map<Integer, Integer>> events) {
        if (events == null || events.size() == 0) {
            return new ArrayList<>();
        }
        List<DFWEvent> dfwEventList = new ArrayList<>();
        Random random = new Random();
        for (Map<Integer, Integer> map : events) {
            List<Integer> weightList = new ArrayList<>();
            List<Integer> eventIdList = new ArrayList<>();
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                eventIdList.add(entry.getKey());
                weightList.add(entry.getValue());
            }

            if (eventIdList.size() == 0) {
                continue;
            }

            int eventId = eventIdList.get(RandomHelper.getRandomIndexByWeight(weightList, random));
            dfwEventList.add(dfwConfig.getDfwEventMap().get(eventId));
        }
        return dfwEventList;
    }

    /**
     * 获取活动activityId对象
     *
     * @param activityId
     * @return
     */
    public static CrossDfwUnionData getDFWData(int activityId, int groupId) {
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
            return null;
        }

        Map<Integer, CrossDfwUnionData> map = dfwGroupDataMap.get(activityId);
        if (map == null) {
            synchronized (lockObject) {
                if (!dfwGroupDataMap.containsKey(activityId)) {
                    dfwGroupDataMap.put(activityId, new ConcurrentHashMap<>());
                }
                map = dfwGroupDataMap.get(activityId);
            }
        }

        CrossDfwUnionData data = map.get(groupId);
        if (data == null) {
            synchronized (lockObject) {
                if (!map.containsKey(groupId)) {

                    // 【生成数据】

                    CrossDfwUnionData dfwData = new CrossDfwUnionData(activityId, groupId);
                    dfwData.setActivityInfo(getDfwConfig(activityId).getActivityInfo());

                    Map<Integer, Map<String, List<DFWUnionRecord>>> recordMap = new CrossDFWUnionRecordDaoImpl().getDFWUnionRecordMap(activityId, groupId);
                    dfwData.setZaoYaoMap(recordMap.get(1)); // 1造谣
                    dfwData.setZhuFuMap(recordMap.get(2)); // 2祝福

                    dfwData.setUnionDataMap(new CrossDFWUnionDataDaoImpl().getDFWUnionDataMap(activityId, groupId));

                    dfwData.setUserCollectDataMap(new CrossDFWUserCollectDataDaoImpl().getDFWUserCollectDataMap(activityId, groupId));

                    // 初始化商会记录最大ID
                    dfwData.setNextRecordId(new AtomicInteger(1 + getUnionRecordMaxId(dfwData)));

                    map.put(groupId, dfwData);
                }
            }
            data = map.get(groupId);
        }

        return data;
    }

    public static DFWConfig getDfwConfig(int activityId) {

        DFWConfig dfwConfig = dfwConfigMap.get(activityId);
        if (dfwConfig != null) {
            return dfwConfig;
        }

        ActivityInfo info = ActivityInfoMgr.getActivityInfo(activityId);
        if (info == null) {
            return null;
        }

        synchronized (lockObject) {
            if (!dfwConfigMap.containsKey(activityId)) {

                DFWConfig tmpDFWConfig = new DFWConfig();

                tmpDFWConfig.setActivityInfo(info);

                int tmpActivityId = tmpDFWConfig.getActivityInfo().getActivityId();
                tmpDFWConfig.setDfwBuildingConfigMap(DFWActivityBussiness.getDFWBuildingConfigMap(tmpActivityId));
                tmpDFWConfig.setDfwEventMap(DFWActivityBussiness.getDFWEventConfigMap(tmpActivityId));
                tmpDFWConfig.setBossConfigMap(DFWActivityBussiness.getDFWBossConfigMap(tmpActivityId));
                tmpDFWConfig.setDfwMapConfigList(DFWActivityBussiness.getDFWMapConfigList(tmpActivityId));

                // 初始化技能配置
                Map<eDaFuWengEventType, List<DFWEvent>> tmpSkillMap = buildSkillMap(tmpDFWConfig.getDfwEventMap());
                tmpDFWConfig.setSkillMap(tmpSkillMap);

                Map<eDaFuWengParamType, DFWParamConfig> paramConfigMap = DFWActivityBussiness.getDFWParamConfigMap(tmpActivityId);
                // 体力配置
                tmpDFWConfig.setMaxEnergy(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_MAX_ENERGY).getValue()));
                tmpDFWConfig.setInitEnergy(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_INIT_ENERGY).getValue()));
                tmpDFWConfig.setEnergyRecoverySecond(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ENERGY_RECOVERY_SECOND).getValue()));
                // 商会配置
                List<Integer> additionDuration = StringUtils.stringToIntegerList(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_UNION_ADDITION_DURATION).getValue(), ";");
                tmpDFWConfig.setUnionMaxAddition(additionDuration.get(0));
                tmpDFWConfig.setUnionMinAddition(additionDuration.get(1));
                tmpDFWConfig.setZhuFuAddition(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ZHUFU_ADDITION).getValue()));
                tmpDFWConfig.setZhuFuNewsCount(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ZHUFU_RECORD_COUNT).getValue()));
                tmpDFWConfig.setZaoYaoAddition(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ZAOYAO_ADDITION).getValue()));
                tmpDFWConfig.setZaoYaoNewsCount(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ZAOYAO_RECORD_COUNT).getValue()));
                tmpDFWConfig.setUnionAdditionRecoverySecond(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_UNION_ADDITION_RECOVERY_SECOND).getValue()));
                tmpDFWConfig.setUnionBeatBackTimes(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_UNION_BEAT_BACK_TIMES).getValue()));
                tmpDFWConfig.setZaoYaoNewsCount(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ZAOYAO_RECORD_COUNT).getValue()));
                tmpDFWConfig.setEffectiveNewsCount(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_UNION_EFFECTIVE_NEWS_COUNT).getValue()));
                tmpDFWConfig.setUnEffectiveNewsCount(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_UNION_UNEFFECTIVE_NEWS_COUNT).getValue()));
                tmpDFWConfig.setRandomCardId(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_RANDOM_CARD_ID).getValue()));
                // 战斗配置
                tmpDFWConfig.setBaseDamage(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_BATTLE_BASE_DAMAGE).getValue()));
                tmpDFWConfig.setFreeBattleTimes(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_BATTLE_FREE_TIMES).getValue()));
                tmpDFWConfig.setBattleCost(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_BATTLE_COST).getValue());
                // 卡片配置
                tmpDFWConfig.setCardIdList(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ALL_CARD_ID_LIST).getValue());
                List<Integer> cardIdList = StringUtils.stringToIntegerList(tmpDFWConfig.getCardIdList(), ";");
                Map<Integer, eDaFuWengCardType> cardTypeMap = new ConcurrentHashMap<>();
                int i = 0;
                cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.Gold);
                cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.YaoYan);
                cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.ZhuFu);
                cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.Energy);
                cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.LuZhang);
                tmpDFWConfig.setYongBingCardDamage(initYongBingCardDamage(tmpDFWConfig, cardIdList.get(i))); // 缓存下佣兵卡伤害
                cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.YongBing);
                cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.QingShen);
                cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.HuoWu);
                cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.ZhuiBu);
                tmpDFWConfig.setCardConfigMap(cardTypeMap);
                // 人偶配置
                tmpDFWConfig.setDollIdList(StringUtils.stringToIntegerList(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ALL_DOLL_ID_LIST).getValue(), ";"));
                for (Integer dollId : tmpDFWConfig.getDollIdList()) {
                    GoodsInfo goodsInfo = TempCommonMgr.getGoodsInfo(dollId);
                    if (goodsInfo != null && goodsInfo.getParamList().get(0).compareTo(BigInteger.ZERO) == 0) {
                        tmpDFWConfig.setDefaultDollId(dollId);
                        break;
                    }
                }
                //密道配置
                tmpDFWConfig.setSecretBigRewardNumWeight(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_SECRET_BIG_REWARD_NUM_WEIGHT).getValue());
                tmpDFWConfig.setSecretBigRewardPool(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_SECRET_BIG_REWARD_POOL).getValue());
                tmpDFWConfig.setSecretNormalRewardPool(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_SECRET_NORMAL_REWARD_POOL).getValue());
                tmpDFWConfig.setSecretReRollPr(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_SECRET_RE_ROLL_PR).getValue());

                // 用户打理所需金币
                tmpDFWConfig.setAutoEventUnlockGold(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_AUTO_EVENT_GOLD_SCORE).getValue());
                tmpDFWConfig.setTenRollUnlock(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_TEN_UNLOCK).getValue());
                // 体力恢复道具ID
                tmpDFWConfig.setEnergyItemId(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ENERGY_ITEM_ID).getValue()));
                // 展示的皮肤
                tmpDFWConfig.setSkinIdList(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_SHOW_SKIN_ID_LIST).getValue());

                // 商会返利事件解析
                String rebateParam = paramConfigMap.get(eDaFuWengParamType.MONOPOLY_BUG_GIFTS_RETURN_REWARDS).getValue();
                List<String> rebateParamStringList = StringUtils.stringToStringList(rebateParam, "\\|");
                Map<Integer, DFWRebateConfig> rebateMap = new ConcurrentHashMap<>();
                for (String param : rebateParamStringList) {
                    List<String> p = StringUtils.stringToStringList(param, "-");
                    DFWRebateConfig dfwRebateConfig = new DFWRebateConfig();
                    dfwRebateConfig.setTimes(Integer.valueOf(p.get(0)));
                    dfwRebateConfig.setRewards(p.get(1));
                    rebateMap.put(dfwRebateConfig.getTimes(), dfwRebateConfig);
                }
                tmpDFWConfig.setRebateConfigMap(rebateMap);

                dfwConfigMap.put(activityId, tmpDFWConfig);
            }
        }

        return dfwConfigMap.get(activityId);
    }

    /**
     * 获取商会数据
     */
    public static DFWUnionData getUnionData(int activityId, String unionUid) {
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return null;
        }

        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionUid);
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
            return null;
        }

        CrossDfwUnionData dfwData = getDFWData(activityId, groupId);
        if (dfwData == null) {
            return null;
        }

        Map<String, DFWUnionData> unionMap = dfwData.getUnionDataMap();

        DFWUnionData unionData = unionMap.get(unionUid);
        if (unionData == null) {
            synchronized (lockObject) {
                if (!unionMap.containsKey(unionUid)) {
                    // 【生成数据】
                    DFWUnionData data = new DFWUnionData();
                    data.setActivityId(activityId);
                    data.setGroupId(groupId);
                    data.setUnionUid(unionUid);
                    data.setBuyTimesMap(new ConcurrentHashMap<>());
                    data.setRebateUserList(new ConcurrentHashMap<>());
                    data.setCollectCountMap(new ConcurrentHashMap<>());
                    data.setAddition(0);
                    data.setAdditionRecoveryTime(System.currentTimeMillis());
                    data.setBuyTimesMap(new ConcurrentHashMap<>());
                    data.setRebateUserList(new ConcurrentHashMap<>());
                    data.setLastResetTime(System.currentTimeMillis());
                    data.setInsertOption();
                    unionMap.put(unionUid, data);
                }
                unionData = unionMap.get(unionUid);
            }
        }

        // 每日重置
        synchronized (lockObject) {
            long today = LocalDateTimeHelper.getZeroTimeTimeStamp();
            if (today > unionData.getLastResetTime()) {
                unionData.setBuyTimesMap(new ConcurrentHashMap<>());
                unionData.setRebateUserList(new ConcurrentHashMap<>());
                if (unionData.getCollectCountMap().containsKey(eItemId.DFW_COLLECT_TIE_QI.getValue())) {
                    unionData.getCollectCountMap().put(eItemId.DFW_COLLECT_TIE_QI.getValue(), 0);
                    unionData.setUpdateOption();
                }
                unionData.setLastResetTime(System.currentTimeMillis());
            }
        }

        return unionData;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    /**
     * 初始化佣兵卡伤害
     */
    public static int initYongBingCardDamage(DFWConfig config, int cardId) {
        GoodsInfo goodsInfo = TempCommonMgr.getGoodsInfo(cardId);
        int eventId = Integer.valueOf(goodsInfo.getExtendParam().split(";")[0]);
        DFWEvent event = config.getDfwEventMap().get(eventId);
        return event.getParamList().get(0);
    }

    /**
     * 是否是人偶道具
     */
    public static boolean isDollItem(int activityId, int goodsId) {
        DFWConfig config = getDfwConfig(activityId);
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return config.getDollIdList().contains(goodsId);
        }
        return false;
    }


    /**
     * 通知商会数据
     */
    public static void notifyUnionData(int activityId, String unionId, long serverId, long userId) {
        DFWUnionData dfwUnionData = getUnionData(activityId, unionId);
        if (dfwUnionData != null) {
            YanQuMessage message = YanQuMessageUtils.buildMessage(ClientProtocol.U_DA_FU_WENG_UNION_DATA, CrossDaFuWengPb.getUnionDataMsg(dfwUnionData));
            MessageHelper.sendPacket(serverId, userId, message);
        }
    }

    public static void notifyUnionDataToAllMember(int activityId, String unionId) {
        DFWUnionData dfwUnionData = getUnionData(activityId, unionId);
        if (dfwUnionData != null) {

            List<Long> serverList = new ArrayList<>();
            int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionId);
            if (groupId == UnionActivityGroupHelper.NO_NEED_GROUP_ID) {
                serverList = ActivityInfoMgr.getActivityInfo(activityId).getServerIdList();
            } else {
                UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, groupId);
                if (groupData != null) {
                    serverList = new ArrayList<>(groupData.getServerSet());
                }
            }

            for (Long serverId : serverList) {
                MonopolyProto.SyncUnionDataMsg.Builder syncMsg = MonopolyProto.SyncUnionDataMsg.newBuilder();
                MonopolyProto.UnionDataMsg.Builder unionDataMsg = CrossDaFuWengPb.getUnionDataMsg(dfwUnionData);
                syncMsg.setActivityId(activityId);
                syncMsg.setUnionId(unionId);
                syncMsg.setUnionMsg(unionDataMsg);
                YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_DA_FU_WENG_CROSS_UNION_SYNC_DATA, syncMsg);
                MessageHelper.sendPacket(serverId, 0, message);
            }
        }
    }

    /**
     * 退出商会通知商会数据置零
     */
    public static void notifyEmptyUnionData(int activityId, Map<Long, Long> userMap, String unionId) {
        DFWConfig dfwConfig = getDfwConfig(activityId);
        if (dfwConfig == null || !ActivityMgr.activityInShowTime(dfwConfig.getActivityInfo())) {
            return;
        }
        if (userMap != null) {
            for (Map.Entry<Long, Long> entry : userMap.entrySet()) {
                Long serverId = entry.getValue();
                Long userId = entry.getKey();
                MonopolyProto.UnionDataMsg.Builder msg = CrossDaFuWengPb.getEmptyUnionDataMsg();
                YanQuMessage message = YanQuMessageUtils.buildMessage(ClientProtocol.U_DA_FU_WENG_UNION_DATA, msg);
                MessageHelper.sendPacket(serverId, userId, message);
            }

        }
        Map<Long, CrossUnionMember> memberMap = getUnionMemberMap(unionId);
        if (memberMap != null) {
            for (CrossUnionMember member : new ArrayList<>(memberMap.values())) {
                syncDFWUserData(member.getServerId(), member.getUserId());
            }
        }
    }

    private static void syncDFWUserData(long serverId, long userId) {

    }

    public static void unionMemberChange(int activityId, List<CrossUnionMember> memberList, String unionId) {
        DFWConfig dfwConfig = getDfwConfig(activityId);
        if (dfwConfig != null && ActivityMgr.activityInShowTime(dfwConfig.getActivityInfo())) {

           /* for (CrossUnionMember member : memberList) {
                syncUnionMemberDoll(player, null);
            }*/
        }
    }

    /**
     * 同步商会成员人偶数据
     */
    public static void syncUnionMemberDoll(int activityId, String unionId, long userId, List<Long> memberList, MonopolyProto.UnionMemberDollTemp.Builder sendPlayer) {
      /*  MonopolyProto.SyncUnionMemberDollRespMsg.Builder respMsg = MonopolyProto.SyncUnionMemberDollRespMsg.newBuilder();
        if (!StringUtils.isNullOrEmpty(unionId)) {
            DFWUnionData unionData = getUnionData(activityId, unionId);
            for (long memberId : memberList) {
                DFWUserData userData = getUserData(activityId, memberId);
                if (userData != null && userData.getUserId() != userId && (sendPlayer == null || sendPlayer.getUserId() != userData.getUserId())) {
                    respMsg.addUnionMemberDoll(CrossDaFuWengPb.parseUnionMemberDollTemp(userData, member.getUserBaseInfo()));
                }
            }
            if (sendPlayer != null) {
                respMsg.addUnionMemberDoll(sendPlayer);
            }
        }
        player.sendChannelPacket(ClientProtocol.U_DA_FU_WENG_SYNC_UNION_MEMBER_DOLL, respMsg);*/
    }

    /**
     * 领取返利奖励
     */
    public static void getRebateReward(int activityId, long serverId, long userId, String unionId, int times, int memberCount) {
        MonopolyProto.GetRebateRewardRespMsg.Builder builder = MonopolyProto.GetRebateRewardRespMsg.newBuilder();
        builder.setRet(0);

        DFWConfig config = getDfwConfig(activityId);
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            sendMsg(serverId, userId, YanQuMessageUtils.buildMessage(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder));
            return;
        }

        DFWRebateConfig rebateConfig = config.getRebateConfigMap().get(times);
        if (rebateConfig == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_DFW_PARAM_ERROR);
            YanQuMessage message = YanQuMessageUtils.buildMessage(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
            sendMsg(serverId, userId, message);
            return;
        }

        synchronized (lockObject) {
            if (StringUtils.isNullOrEmpty(unionId)) {
                builder.setRet(GameErrorCode.E_UNION_NO_JOIN_UNION);
                YanQuMessage message = YanQuMessageUtils.buildMessage(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
                sendMsg(serverId, userId, message);
                return;
            }


            DFWUnionData dfwUnionData = getUnionData(config.getActivityInfo().getActivityId(), unionId);
            if (dfwUnionData.getBuyTimes() < times) {
                // 商会购买次数不满足
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_BUY_TIMES_NOT_ENOUGH);
                YanQuMessage message = YanQuMessageUtils.buildMessage(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
                sendMsg(serverId, userId, message);
                return;
            }

            if (dfwUnionData.getRebateUserList().containsKey(times) && dfwUnionData.getRebateUserList().get(times).size() >= memberCount) {
                // 超出领奖人数
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_REWARD_PEOPLE_FULL);
                YanQuMessage message = YanQuMessageUtils.buildMessage(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
                sendMsg(serverId, userId, message);
                return;
            }

            if (dfwUnionData.getRebateUserList().containsKey(times) && dfwUnionData.getRebateUserList().containsKey(userId)) {
                // 奖励已领取
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_HAS_GET_REWARD);
                YanQuMessage message = YanQuMessageUtils.buildMessage(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
                sendMsg(serverId, userId, message);
                return;
            }

            // 增加商会领奖记录
            if (!dfwUnionData.getRebateUserList().containsKey(times)) {
                dfwUnionData.getRebateUserList().put(times, new ArrayList<>());
            }
            dfwUnionData.getRebateUserList().get(times).add(userId);
            dfwUnionData.setUpdateOption();

            // 添加奖励
            CrossMonopolyProto.CrossDfwUnionRebateRespMsg.Builder resp = CrossMonopolyProto.CrossDfwUnionRebateRespMsg.newBuilder();
            resp.setActivityId(activityId);
            resp.setUnionId(unionId);
            resp.setTimes(times);
            YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_DA_FU_WENG_CROSS_UNION_REBATE, resp);
            MessageHelper.sendPacket(serverId, userId, message);
            syncDFWUserData(serverId, userId);
        }

    }

    private static void sendMsg(long serverId, long userId, YanQuMessage message) {
        MessageHelper.sendPacket(serverId, userId, message);
    }

    public static void addUnionBuyTimes(int activityId, long serverId, long userId, String unionId) {
        if (!StringUtils.isNullOrEmpty(unionId)) {
            DFWUnionData dfwUnionData = getUnionData(activityId, unionId);
            if (dfwUnionData != null) {
                dfwUnionData.addBuyTimes(userId);
                dfwUnionData.setUpdateOption();
            }
        }
        notifyUnionData(activityId, unionId, serverId, userId);
        notifyUnionDataToAllMember(activityId, unionId);
        // syncUnionMemberDoll(player, null);
        syncDFWUserData(serverId, userId);
    }


    private static void addResultReward(DFWTenRollResult result, MonopolyProto.RollDiceRespMsg.Builder rollDiceRespMsg) {
        for (MonopolyProto.MovePositionMsg.Builder movePosition : rollDiceRespMsg.getMovePositionListBuilderList()) {
            if (movePosition.hasSecretRoadReward()) {
                result.addProperty(PropertyHelper.parseStringToProperty(movePosition.getSecretRoadReward()));
            } else {
                List<MonopolyProto.EventResultMsg> eventList = movePosition.getEventListList();
                for (MonopolyProto.EventResultMsg eventResultMsg : eventList) {
                    if (eventResultMsg.getEventId() != 0 && !eventResultMsg.getCollectLimit()) {
                        result.addProperty(PropertyHelper.parseStringToProperty(eventResultMsg.getReward()));
                    }
                }
            }
        }
    }


    public static void zhuFuCard(int activityId, long serverId, long userId, String unionUid, UserBaseInfo userBaseInfo, MonopolyProto.UseCardRespMsg.Builder respMsg, int groupId) {
        // 看看自己是否有商会
        if (StringUtils.isNullOrEmpty(unionUid)) {
            respMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_NO_UNION);
            return;
        }

        DFWUnionData unionData = getUnionData(activityId, unionUid);
        synchronized (lockObject) {
            checkUnionAddition(getDfwConfig(activityId), unionUid);
            if (unionData.getAddition() >= getDfwConfig(activityId).getUnionMaxAddition()) {
                respMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_ZHU_FU_MAX);
                return;
            }
            //祝福加成
            changeAddition(getDfwConfig(activityId).getZhuFuAddition(), unionData);
        }
        // 添加
        MonopolyProto.MonopolyPlayerMsg.Builder builder = MonopolyProto.MonopolyPlayerMsg.newBuilder();
        builder.setUserId(userId);
        builder.setPlayer(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        addUnionRecord(unionUid, getDfwConfig(activityId).getActivityInfo().getActivityId(), builder.build(), 2, groupId);
        // 同步
        syncZhuFu(activityId, userId, userBaseInfo.getNickName(), unionUid, groupId);
        respMsg.setRet(0);
    }


    /**
     * 检查商会加成
     */
    public static void checkUnionAddition(DFWConfig config, String unionUid) {
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return;
        }
        int activityId = config.getActivityInfo().getActivityId();
        DFWUnionData unionData = getUnionData(activityId, unionUid);
        int curAddition = unionData.getAddition();
        if (curAddition == 0) {
            return;
        }
        CalcPowerResult result = calAddition(config.getActivityInfo().getActivityId(), unionData.getAdditionRecoveryTime(), config.getUnionAdditionRecoverySecond() * 1000, 10, unionData.getAddition());
        if (result.getCurPower() != unionData.getAddition()) {
            unionData.setAddition(result.getCurPower());
            unionData.setAdditionRecoveryTime(result.getLastRecoverTime());
            notifyUnionDataToAllMember(activityId, unionUid);
        }
    }

    /**
     * 商会加成恢复计算
     */
    public static CalcPowerResult calAddition(int activityId, long lastRestoreTime, long recoverDuration, int recoverValuePerTimes, int curAddition) {

        long now = System.currentTimeMillis();
        if (curAddition == 0) {
            // 没有加成不需要变化了
            return new CalcPowerResult(curAddition, now);
        }
        int addTimes = (int) ((now - lastRestoreTime) / recoverDuration);
        boolean aboveZero = curAddition > 0;
        int addAddition = addTimes * recoverValuePerTimes;
        if (aboveZero) {
            // 祝福效果要扣
            addAddition = addAddition * -1;
        }
        curAddition = curAddition + addAddition;
        if ((aboveZero && curAddition < 0) || (!aboveZero && curAddition > 0)) {
            // 祝福不能扣到负数 || 造谣不能加到正数
            curAddition = 0;
        }
        lastRestoreTime = lastRestoreTime + addTimes * recoverDuration;
        if (curAddition > getDfwConfig(activityId).getUnionMaxAddition()) {
            curAddition = getDfwConfig(activityId).getUnionMaxAddition();
            lastRestoreTime = now;
        } else if (curAddition < getDfwConfig(activityId).getUnionMinAddition()) {
            curAddition = getDfwConfig(activityId).getUnionMinAddition();
            lastRestoreTime = now;
        }

        return new CalcPowerResult(curAddition, lastRestoreTime);
    }


    /**
     * 同步祝福信息给商会成员
     */
    public static void syncZhuFu(int activityId, long userId, String nickName, String unionUid, int groupId) {
        List<Long> serverList = new ArrayList<>();
        if (groupId == UnionActivityGroupHelper.NO_NEED_GROUP_ID) {
            serverList = ActivityInfoMgr.getActivityInfo(activityId).getServerIdList();
        } else {
            UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, groupId);
            if (groupData != null) {
                serverList = new ArrayList<>(groupData.getServerSet());
            }
        }

        for (Long serverId : serverList) {
            MonopolyProto.SyncZhufuMsg.Builder syncMsg = MonopolyProto.SyncZhufuMsg.newBuilder();
            syncMsg.setActivityId(activityId);
            syncMsg.setUnionId(unionUid);
            MonopolyProto.SyncZhuFuRespMsg.Builder builder = MonopolyProto.SyncZhuFuRespMsg.newBuilder();
            builder.setName(nickName);
            syncMsg.setZhufuMsg(builder);
            syncMsg.setUnionMsg(CrossDaFuWengPb.getUnionDataMsg(getUnionData(activityId, unionUid)));
            sendMsg(serverId, userId, YanQuMessageUtils.buildMessage(GameProtocol.S_DA_FU_WENG_CROSS_UNION_SYNC_ZHUFU, syncMsg));
        }

    }

    public static void addUnionRecord(String unionUid, int activityId, MonopolyProto.MonopolyPlayerMsg monopolyPlayerMsg, int type, int groupId) {
        CrossDfwUnionData dfwData = getDFWData(activityId, groupId);
        Map<String, List<DFWUnionRecord>> recordMap;
        DFWUnionRecord record = new DFWUnionRecord();
        record.setActivityId(activityId);
        record.setGroupId(groupId);
        record.setUserId(monopolyPlayerMsg.getUserId());
        record.setUserBaseInfo(PlayerBasePb.parseBaseUserInfo(monopolyPlayerMsg.getPlayer()));
        record.setCreateTime(System.currentTimeMillis());
        record.setServerId(monopolyPlayerMsg.getPlayer().getServerId());
        record.setUnionUid(unionUid);
        record.setRecordType(type);
        record.setInsertOption();
        if (type == 1) {
            recordMap = dfwData.getZaoYaoMap();
            record.setBeatBackTimes(0);
        } else if (type == 2) {
            recordMap = dfwData.getZhuFuMap();
        } else {
            return;
        }
        if (!recordMap.containsKey(unionUid)) {
            recordMap.put(unionUid, new ArrayList<>());
        }
        List<DFWUnionRecord> dfwUnionRecords = recordMap.get(unionUid);
        record.setRecordId(dfwData.getNextRecordId());
        dfwUnionRecords.add(record);
    }

    /**
     * 加成修改
     */
    public static void changeAddition(int changeAddition, DFWUnionData unionData) {
        DFWConfig dfwConfig = getDfwConfig(unionData.getActivityId());
        checkUnionAddition(dfwConfig, unionData.getUnionUid());
        if (unionData.getAddition() == 0) {
            unionData.setAdditionRecoveryTime(System.currentTimeMillis());
        }
        if (changeAddition > 0) {
            int maxAddition = dfwConfig.getUnionMaxAddition();
            if (unionData.getAddition() + changeAddition > maxAddition) {
                unionData.setAddition(maxAddition);
                unionData.setAdditionRecoveryTime(System.currentTimeMillis());
            } else {
                unionData.setAddition(unionData.getAddition() + changeAddition);
            }
        } else if (changeAddition < 0) {
            int minAddition = dfwConfig.getUnionMinAddition();
            if (unionData.getAddition() + changeAddition < minAddition) {
                unionData.setAddition(minAddition);
                unionData.setAdditionRecoveryTime(System.currentTimeMillis());
            } else {
                unionData.setAddition(unionData.getAddition() + changeAddition);
            }
        }
        notifyUnionDataToAllMember(unionData.getActivityId(), unionData.getUnionUid());

    }

    /**
     * 获取全部unionRecord
     */
    private static List<DFWUnionRecord> getUnionRecordList(int type, int activityId, String unionUid, int groupId) {
        CrossDfwUnionData dfwData = getDFWData(activityId, groupId);
        if (type == 1) {
            Map<String, List<DFWUnionRecord>> zaoYaoMap = dfwData.getZaoYaoMap();
            if (!zaoYaoMap.containsKey(unionUid)) {
                zaoYaoMap.put(unionUid, new ArrayList<>());
            }
            return zaoYaoMap.get(unionUid);
        } else if (type == 2) {
            Map<String, List<DFWUnionRecord>> zhuFuMap = dfwData.getZhuFuMap();
            if (!zhuFuMap.containsKey(unionUid)) {
                zhuFuMap.put(unionUid, new ArrayList<>());
            }
            return zhuFuMap.get(unionUid);
        }
        return new ArrayList<>();
    }

    /**
     * 获取造谣祝福记录
     *
     * @param type 1造谣，2祝福
     */
    public static List<DFWUnionRecord> getUnionRecord(int activityId, String unionUid, int type, int groupId) {
        synchronized (lockObject) {
            int maxCount = 0;
            List<DFWUnionRecord> list = getUnionRecordList(type, activityId, unionUid, groupId);
            DFWConfig config = getDfwConfig(activityId);
            if (type == 1) {
                maxCount = config.getZaoYaoNewsCount();
            } else if (type == 2) {
                maxCount = config.getZhuFuNewsCount();
            }

            List<DFWUnionRecord> retList;
            if (list.size() <= maxCount) {
                retList = new ArrayList<>(list);
            } else {
                int size = list.size();
                retList = new ArrayList<>(list.subList(size - maxCount, size));
            }
            Collections.reverse(retList);
            return retList;
        }
    }


    /**
     * 获取情报事件信息 商会成员列表
     *
     * @param unionUid
     * @param itemId
     * @param memberIdList
     */
    public static void getCollectEventMemberList(int activityId, long serverId, long userId, String unionUid, int itemId, List<Long> memberIdList, int groupId) {
        synchronized (lockObject) {
            MonopolyProto.CollectMemberRespMsg.Builder respMsg = MonopolyProto.CollectMemberRespMsg.newBuilder();
            int timeMark = getTimeMark();
            CrossDfwUnionData dfwData = getDFWData(activityId, groupId);
            Map<Integer, Map<String, Map<Integer, Map<Integer, Map<Long, DFWUserCollectData>>>>> userCollectDataMap = dfwData.getUserCollectDataMap();
            Map<Long, Map<Integer, DFWUserCollectData>> dataMap = new ConcurrentHashMap<>();
            //宝箱额外处理
            if (itemId == 110002) {
                for (Long memberId : memberIdList) {
                   /* DFWUserData userData = getUserData(activityId, member.getUserId());
                    if (userData.getBoxOpenTimes() > 0) {
                        dataMap.put(userData.getUserId(), new ConcurrentHashMap<>());
                        DFWUserCollectData data = new DFWUserCollectData();
                        data.setValue(userData.getBoxOpenTimes());
                        dataMap.get(userData.getUserId()).put(getTimeMark(), data);
                    }*/
                }
            } else {
                if (userCollectDataMap.containsKey(activityId)) {
                    if (userCollectDataMap.get(activityId).containsKey(unionUid)) {
                        if (userCollectDataMap.get(activityId).get(unionUid).containsKey(itemId)) {
                            for (Map.Entry<Integer, Map<Long, DFWUserCollectData>> entry : userCollectDataMap.get(activityId).get(unionUid).get(itemId).entrySet()) {
                                for (Map.Entry<Long, DFWUserCollectData> data : entry.getValue().entrySet()) {
                                    if (!dataMap.containsKey(data.getKey())) {
                                        dataMap.put(data.getKey(), new ConcurrentHashMap<>());
                                    }
                                    dataMap.get(data.getKey()).put(entry.getKey(), data.getValue());
                                }
                            }
                        }
                    }
                }
            }
            //userId-timeMark
            for (Map.Entry<Long, Map<Integer, DFWUserCollectData>> map : dataMap.entrySet()) {
                MonopolyProto.CollectMemberTempMsg.Builder temp = MonopolyProto.CollectMemberTempMsg.newBuilder();
                temp.setPlayerInfo(PlayerBasePb.parsePlayerBaseTempMsg(CrossUserMgr.getUserBaseInfo(map.getKey())));
                int todayScore = 0;
                if (map.getValue().get(timeMark) != null) {
                    todayScore = map.getValue().get(timeMark).getValue();
                }
                temp.setTodayValue(todayScore);
                int totalScore = 0;
                for (DFWUserCollectData data : map.getValue().values()) {
                    totalScore += data.getValue();
                }
                temp.setTotalValue(totalScore);
                respMsg.addCollectMmberTemp(temp);
            }
            respMsg.setRet(0);
            sendMsg(serverId, userId, YanQuMessageUtils.buildMessage(ClientProtocol.U_DA_FU_WENG_GET_COLLECT_EVENT_MEMBER_LIST, respMsg));
        }

    }

    /**
     * 初始化技能Map
     */
    public static Map<eDaFuWengEventType, List<DFWEvent>> buildSkillMap(Map<Integer, DFWEvent> eventMap) {
        Map<eDaFuWengEventType, List<DFWEvent>> map = new ConcurrentHashMap<>();
        map.put(eDaFuWengEventType.MapSkill, new ArrayList<>());
        map.put(eDaFuWengEventType.BattleSkill, new ArrayList<>());
        map.put(eDaFuWengEventType.OpenBoxSkill, new ArrayList<>());
        map.put(eDaFuWengEventType.RecoverySkill, new ArrayList<>());
        map.put(eDaFuWengEventType.DollSkill1, new ArrayList<>());
        map.put(eDaFuWengEventType.DollSKill2, new ArrayList<>());
        map.put(eDaFuWengEventType.GodSkill, new ArrayList<>());
        map.put(eDaFuWengEventType.MoveSkill, new ArrayList<>());
        for (DFWEvent event : eventMap.values()) {
            eDaFuWengEventType eventType = event.getEventType();
            if (map.containsKey(eventType)) {
                // 配置了升级参数的技能只要存0级的
                if (eventType == eDaFuWengEventType.BattleSkill || eventType == eDaFuWengEventType.OpenBoxSkill) {
                    if (event.getUpgradeParamList().get(0) != 0) {
                        continue;
                    }
                }
                map.get(event.getEventType()).add(event);
            }
        }
        return map;
    }

    /**
     * 根据金币获取地图加成
     *
     * @param goldScore 金币积分数
     * @return 千分比，List：0金币加成
     */
    public static List<Integer> getMapSkillAddition(DFWConfig config, int goldScore) {
        List<Integer> addition = new ArrayList<>();
        addition.add(0);
        // 找当前地图
        DFWMapConfig lastMap = null;
        for (DFWMapConfig mapConfig : config.getDfwMapConfigList()) {
            if (goldScore >= mapConfig.getUnlockGold()) {
                lastMap = mapConfig;
            } else {
                break;
            }
        }
        if (lastMap == null) {
            return addition;
        }
        // 找技能事件
        if (lastMap.getSkill() == 0) {
            return addition;
        }
        DFWEvent event = config.getDfwEventMap().get(lastMap.getSkill());
        if (event == null) {
            getLogger().error("DaFuWengMgr getMapSkillAddition error! Map skill mapper DFWEvent no found!");
            return addition;
        }
        addition.set(0, event.getParamList().get(0));
        return addition;
    }

    /**
     * 获取战斗技能加成（其利断金）
     *
     * @return 战斗伤害加成值
     */
    public static int getBattleSkillAddition(int activityId, String unionUid) {
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return 0;
        }
        DFWConfig config = getDfwConfig(activityId);
        if (config == null) {
            return 0;
        }
        int skillEventId = getBattleSkillEventId(config, unionUid);
        DFWEvent skill = config.getDfwEventMap().get(skillEventId);
        if (skill == null) {
            return 0;
        } else {
            return skill.getParamList().get(0);
        }
    }

    /**
     * 获取当前其利断金事件ID
     */
    public static int getBattleSkillEventId(DFWConfig config, String unionUid) {
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return 0;
        }
        DFWUnionData unionData = getUnionData(config.getActivityInfo().getActivityId(), unionUid);
        // 找到0级技能
        List<DFWEvent> skillList = config.getSkillMap().get(eDaFuWengEventType.BattleSkill);
        int count = getIronCollectCount(unionData);
        // 判断技能升级
        DFWEvent skill = skillList.get(0);
        for (int i = 0; i < 100; i++) {
            int upgradeCount = skill.getUpgradeParamList().get(1);
            if (count >= upgradeCount && upgradeCount != 0) {
                // 能升级
                DFWEvent tmpEvent = config.getDfwEventMap().get(skill.getUpgradeParamList().get(2));
                if (tmpEvent != null) {
                    skill = tmpEvent;
                } else {
                    getLogger().error("DaFuWengMgr getBattleSkillAddition error! Upgrade DFWEvent no found!");
                    break;
                }
            } else {
                // 不够升级
                break;
            }
        }
        return skill.getEventId();
    }

    public static int getUnionOpenBoxCount(DFWUnionData unionData) {
        if (unionData == null) {
            return 0;
        }
        DFWConfig dfwConfig = getDfwConfig(unionData.getActivityId());
        int activityId = dfwConfig.getActivityInfo().getActivityId();
        int count = 0;
        // 找用户数据
        Map<Long, CrossUnionMember> unionMemberMap = getUnionMemberMap(unionData.getUnionUid());
        /*Map<Long, DFWUserData> userDataMap = getDFWData(activityId).getUserDataMap();
        for (UnionMember unionMember : unionMemberMap.values()) {
            long userId = unionMember.getUserId();
            if (userDataMap.containsKey(userId)) {
                count += userDataMap.get(userId).getBoxOpenTimes();
            }
        }*/
        return count;
    }

    public static int getIronCollectCount(DFWUnionData unionData) {
        if (unionData == null) {
            return 0;
        }
        DFWConfig dfwConfig = getDfwConfig(unionData.getActivityId());
        // 找到0级技能
        List<DFWEvent> skillList = dfwConfig.getSkillMap().get(eDaFuWengEventType.BattleSkill);
        if (skillList.isEmpty()) {
            getLogger().error("DaFuWengMgr getBattleSkillAddition error! Map skill mapper DFWEvent no found!");
            return 0;
        }
        // 获取已收集数量
        int collectGoodsId = skillList.get(0).getUpgradeParamList().get(3);
        Integer count = unionData.getCollectCountMap().get(collectGoodsId);
        if (count == null) {
            return 0;
        }
        return count;
    }

    /**
     * 获取开箱技能加成（开箱大吉）
     *
     * @return 开箱奖品增加数
     */
    public static int getOpenBoxSkillAddition(DFWConfig config, String unionUid) {
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return 0;
        }
        // 获取次数
        int openBoxTimes = 0;
        Map<Long, CrossUnionMember> unionMemberMap = getUnionMemberMap(unionUid);
       /* for (UnionMember member : unionMemberMap.values()) {
            DFWUserData userData = getUserData(config.getActivityInfo().getActivityId(), member.getUserId());
            openBoxTimes += userData.getBoxOpenTimes();
        }*/
        // 找到0级技能
        List<DFWEvent> skillList = config.getSkillMap().get(eDaFuWengEventType.OpenBoxSkill);
        if (skillList.isEmpty()) {
            getLogger().error("DaFuWengMgr getOpenBoxSkillAddition error! Map skill mapper DFWEvent no found!");
            return 0;
        }
        // 判断技能升级
        DFWEvent skill = skillList.get(0);
        for (int i = 0; i < 100; i++) {
            int upgradeTimes = skill.getUpgradeParamList().get(1);
            if (openBoxTimes >= upgradeTimes && upgradeTimes != 0) {
                // 能升级
                DFWEvent tmpEvent = config.getDfwEventMap().get(skill.getUpgradeParamList().get(2));
                if (tmpEvent != null) {
                    skill = tmpEvent;
                } else {
                    getLogger().error("DaFuWengMgr getOpenBoxSkillAddition error! Upgrade DFWEvent no found!");
                    break;
                }
            } else {
                // 不够升级
                break;
            }
        }
        return skill.getParamList().get(0);
    }

    public static Map<Long, CrossUnionMember> getUnionMemberMap(String unionUid) {
        return new HashMap<>();
    }

    public static void collectGoods(int activityId, String unionId, Property property, long serverId, long userId, long msgId, int groupId) {
        CrossMonopolyProto.CollectEventResultMsg.Builder msg = CrossMonopolyProto.CollectEventResultMsg.newBuilder();
        msg.setMsgId(msgId);
        msg.setCanDoCollectEvent(true);
        msg.setNewBattleSkillId(0);
        msg.setRecachReward(false);
        int beforeBattleSkillId = getBattleSkillEventId(getDfwConfig(activityId), unionId);
        DFWUnionData dfwUnionData = getUnionData(activityId, unionId);
        if (dfwUnionData == null) {
            msg.setCanDoCollectEvent(false);
            msg.setRecachReward(false);
            YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_DA_FU_WENG_CROSS_UNION_COLLECT_RESULT, msg);
            MessageHelper.sendPacket(serverId, userId, message);
            return;
        }
        for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
            int goodsId = entry.getKey();
            int addValue = entry.getValue().intValue();
            if (!dfwUnionData.getCollectCountMap().containsKey(goodsId)) {
                dfwUnionData.getCollectCountMap().put(goodsId, 0);
            }
            updateMemCollect(activityId, unionId, userId, goodsId, addValue);
            // 先判断数据
            int newValue = dfwUnionData.getCollectCountMap().get(goodsId) + addValue;
            //根据获得的道具 取得建筑类型
            int buildingType = getCollectBuildingTypeByCollectItemId(activityId, goodsId);
            getLogger().info("collect {} value {}, oldValue {}, newValue {}", goodsId, addValue, dfwUnionData.getCollectCountMap().get(goodsId), newValue);
            if (buildingType != 0) {
                // 采集任务才进来
                String collectTask = getDfwConfig(activityId).getDfwBuildingConfigMap().get(buildingType).getCollectTask();
                if (!collectTask.equals("0")) {
                    List<Integer> collectParam = StringUtils.stringToIntegerList(collectTask, "=");
                    int taskGoodsId = collectParam.get(0);
                    int taskAddValue = collectParam.get(1);
                    int needAddTaskNum = 0;
                    while (goodsId == taskGoodsId && newValue >= taskAddValue) {
                        // 商会值更新
                        newValue = newValue - taskAddValue;
                        needAddTaskNum++;
                        msg.setRecachReward(true);
                    }
                    if (needAddTaskNum > 0) {

                        List<Long> serverList = new ArrayList<>();
                        if (groupId == UnionActivityGroupHelper.NO_NEED_GROUP_ID) {
                            serverList = ActivityInfoMgr.getActivityInfo(activityId).getServerIdList();
                        } else {
                            UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, groupId);
                            if (groupData != null) {
                                serverList = new ArrayList<>(groupData.getServerSet());
                            }
                        }
                        for (Long sId : serverList) {
                            CrossMonopolyProto.CrossDfwAddUserCollectTaskMsg.Builder taskMsg = CrossMonopolyProto.CrossDfwAddUserCollectTaskMsg.newBuilder();
                            taskMsg.setActivityId(activityId);
                            taskMsg.setUnionId(unionId);
                            taskMsg.setTaskId(taskGoodsId);
                            taskMsg.setAddTimes(needAddTaskNum);
                            YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_DA_FU_WENG_CROSS_UNION_COLLECTION_TASK, taskMsg);
                            MessageHelper.sendPacket(sId, 0, message);
                        }
                    }

                }
            }
            dfwUnionData.getCollectCountMap().put(goodsId, newValue);
        }
        if (!StringUtils.isNullOrEmpty(unionId)) {
            notifyUnionDataToAllMember(activityId, unionId);
        }
        int afterBattleSkillId = getBattleSkillEventId(getDfwConfig(activityId), unionId);
        dfwUnionData.setUpdateOption();
        msg.setNewBattleSkillId(afterBattleSkillId - beforeBattleSkillId);
        YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_DA_FU_WENG_CROSS_UNION_COLLECT_RESULT, msg);
        MessageHelper.sendPacket(serverId, userId, message);
    }

    private static int getCollectBuildingTypeByCollectItemId(int activityId, int goodsId) {
        for (DFWBuildingConfig config : getDfwConfig(activityId).getDfwBuildingConfigMap().values()) {
            String collectTask = config.getCollectTask();
            if (!collectTask.equals("0")) {
                String id = collectTask.split("=")[0];
                if (id.equals(String.valueOf(goodsId))) {
                    return config.getBuildingId();
                }
            }
        }
        return 0;
    }

    /**
     * 获取神的加成
     *
     * @return List：0金币加成千分比，1银币加成千分比，2随机好的恢复体力值，3持续次数
     */
    public static List<Integer> getGodSkillAddition(DFWConfig config, List<DFWGodData> godList) {
        List<Integer> addition = new ArrayList<>();
        addition.add(0);
        addition.add(0);
        addition.add(0);
        addition.add(0);
        if (godList.size() == 0) {
            return addition;
        }
        // 找神事件
        for (DFWGodData godData : godList) {
            int godId = godData.getGodId();
            DFWEvent event = config.getDfwEventMap().get(godId);
            if (event == null || event.getEventType() != eDaFuWengEventType.God) {
                getLogger().error("DaFuWengMgr getGodSkillAddition error! God Event no found!");
                continue;
            }
            // 找技能
            int skillId = event.getParamList().get(0);
            DFWEvent skill = config.getDfwEventMap().get(skillId);
            if (skill.getEventType() == eDaFuWengEventType.RecoverySkill) {
                addition.set(3, skill.getParamList().get(2));
                int random = new Random().nextInt(1000);
                if (random < skill.getParamList().get(1)) {
                    addition.set(2, addition.get(2) + skill.getParamList().get(0));
                }
            } else if (skill.getEventType() == eDaFuWengEventType.GodSkill) {
                addition.set(0, addition.get(0) + skill.getParamList().get(0));
                addition.set(3, skill.getParamList().get(2));
            } else {
                getLogger().error("DaFuWengMgr getGodSkillAddition error! God Skill Type error!");
                continue;
            }
        }
        return addition;
    }


    /**
     * 获取坐骑技能加成
     *
     * @return List：0增加的移动步数，1持续次数
     */
    public static List<Integer> getVehicleSkillAddition(DFWConfig config, int vehicleId) {
        List<Integer> addition = new ArrayList<>();
        addition.add(0);
        addition.add(0);
        DFWEvent event = config.getDfwEventMap().get(vehicleId);
        if (event == null || event.getEventType() != eDaFuWengEventType.Vehicle) {
            getLogger().error("DaFuWengMgr getVehicleSkillAddition error! Skill no found or event type error!");
            return addition;
        }
        int skillId = event.getParamList().get(0);
        DFWEvent skill = config.getDfwEventMap().get(skillId);
        if (skill == null || skill.getEventType() != eDaFuWengEventType.MoveSkill) {
            getLogger().error("DaFuWengMgr getVehicleSkillAddition error! Skill type error!");
            return addition;
        }
        addition.set(0, skill.getParamList().get(0));
        addition.set(1, skill.getParamList().get(2));
        return addition;
    }

    /**
     * 获取商会加成
     *
     * @return List：0金币加成
     */
    public static List<Integer> getUnionSkillAddition(DFWConfig config, String unionUid) {
        List<Integer> addition = new ArrayList<>();
        addition.add(0);
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return addition;
        }
        checkUnionAddition(config, unionUid);
        DFWUnionData unionData = getUnionData(config.getActivityInfo().getActivityId(), unionUid);
        int unionAddition = unionData.getAddition();
        addition.set(0, unionAddition);
        return addition;
    }

    public static void updateMemCollect(int activityId, String unionUid, long userId, int key, int value) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionUid);
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
            return;
        }

        int timeMark = getTimeMark();

        CrossDfwUnionData dfwData = getDFWData(activityId, groupId);
        Map<Integer, Map<String, Map<Integer, Map<Integer, Map<Long, DFWUserCollectData>>>>> userCollectDataMap = dfwData.getUserCollectDataMap();
        if (!userCollectDataMap.containsKey(activityId)) {
            userCollectDataMap.put(activityId, new ConcurrentHashMap<>());
        }
        if (!userCollectDataMap.get(activityId).containsKey(unionUid)) {
            userCollectDataMap.get(activityId).put(unionUid, new ConcurrentHashMap<>());
        }
        if (!userCollectDataMap.get(activityId).get(unionUid).containsKey(key)) {
            userCollectDataMap.get(activityId).get(unionUid).put(key, new ConcurrentHashMap<>());
        }
        if (!userCollectDataMap.get(activityId).get(unionUid).get(key).containsKey(timeMark)) {
            userCollectDataMap.get(activityId).get(unionUid).get(key).put(timeMark, new ConcurrentHashMap<>());
        }
        if (!userCollectDataMap.get(activityId).get(unionUid).get(key).get(timeMark).containsKey(userId)) {
            DFWUserCollectData dfwUserCollectData = new DFWUserCollectData();
            dfwUserCollectData.setActivityId(activityId);
            dfwUserCollectData.setGroupId(groupId);
            dfwUserCollectData.setTimeMark(timeMark);
            dfwUserCollectData.setUnionUid(unionUid);
            dfwUserCollectData.setUserId(userId);
            dfwUserCollectData.setItemId(key);
            dfwUserCollectData.setValue(0);
            dfwUserCollectData.setInsertOption();
            userCollectDataMap.get(activityId).get(unionUid).get(key).get(timeMark).put(userId, dfwUserCollectData);
        }
        userCollectDataMap.get(activityId).get(unionUid).get(key).get(timeMark).get(userId).setValue(userCollectDataMap.get(activityId).get(unionUid).get(key).get(timeMark).get(userId).getValue() + value);
    }

    private static int getTimeMark() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        String monthStr = month < 10 ? "0" + month : month + "";
        String dayStr = day < 10 ? "0" + day : day + "";
        String timeStr = year + monthStr + dayStr;
        return Integer.valueOf(timeStr);
    }


    /**
     * 初始化商会记录最大ID
     */
    private static int getUnionRecordMaxId(CrossDfwUnionData data) {
        int maxId = 0;
        Map<String, List<DFWUnionRecord>> zaoYaoMap = data.getZaoYaoMap();
        Map<String, List<DFWUnionRecord>> zhuFuMap = data.getZhuFuMap();
        for (List<DFWUnionRecord> list : zaoYaoMap.values()) {
            for (DFWUnionRecord record : list) {
                if (record.getRecordId() > maxId) {
                    maxId = record.getRecordId();
                }
            }
        }
        for (List<DFWUnionRecord> list : zhuFuMap.values()) {
            for (DFWUnionRecord record : list) {
                if (record.getRecordId() > maxId) {
                    maxId = record.getRecordId();
                }
            }
        }
        return maxId;
    }

    /**
     * 同步商会情报红点
     */
    public static void syncUnionNewsRedHot(String unionUid) {
        Map<Long, CrossUnionMember> memberMap = getUnionMemberMap(unionUid);
        if (memberMap == null) {
            return;
        }
        WorldMessageProto.RedHotNotifyMsg.Builder redHotMsg = parseRedHotNotifyMsg(eRedHotNotifyType.DaFuWengUnionNews.getValue(), 1, "");
        for (UnionMember member : memberMap.values()) {
//            if (member.getUserId() == userId) {
//                continue; // 现在红点也要推给发现boss的人了
//            }
            YanQuMessage message = YanQuMessageUtils.buildMessage(ClientProtocol.U_RED_HOT_NOTIFY, redHotMsg);
            MessageHelper.sendPacket(member.getUserBaseInfo().getServerId(), member.getUserId(), message);
        }
    }

    public static WorldMessageProto.RedHotNotifyMsg.Builder parseRedHotNotifyMsg(int type, int count, String param) {
        WorldMessageProto.RedHotNotifyMsg.Builder msg = WorldMessageProto.RedHotNotifyMsg.newBuilder();
        msg.setType(type);
        msg.setCount(count);
        if (!StringUtils.isNullOrEmpty(param)) {
            msg.setParam(param);
        }
        return msg;
    }

}
